{extend name="../../base/view/common/base" /}
<!-- 主体 -->
{block name="body"}
<div class="p-page">
    <div class="layui-row layui-col-space15">
        <div class="layui-col-md12">
            <div class="layui-card">
                <div class="layui-card-body">
                    <form class="layui-form toolbar"><div class="layui-form-item">
                            <div class="layui-inline">
                                <input type="text" name="keywords" id="keywords" class="layui-input" placeholder="案由名称" autocomplete="off">
                            </div>
                            <div class="layui-inline">
                                <button class="layui-btn layui-btn-normal" lay-submit lay-filter="searchForm"><i class="layui-icon">&#xe615;</i>搜索
                                </button><button type="button" class="layui-btn layui-btn-primary" id="resetBtn"><i class="layui-icon">&#xe669;</i>清空</button>
                            </div></div>
                    </form>
                    <div style="margin: 10px 0;">
                        <button type="button" class="layui-btn layui-btn-sm layui-btn-success" id="addBtn">
                            <i class="layui-icon">&#xe654;</i>添加案由
                        </button>
                    </div>
                    <table id="treeTable" lay-filter="treeTable"></table>
                </div>
            </div>
        </div>
    </div>
</div>
{/block}

<!-- 表格操作列 -->
{block name="js"}
<script type="text/html" id="tableBar">
    <a class="layui-btn layui-btn-xs" lay-event="add">添加子级</a><a class="layui-btn layui-btn-normal layui-btn-xs" lay-event="edit">编辑</a>
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>

<script>
    const moduleInit = ['tool'];
    function gouguInit() {
        let tool = layui.tool,
            form = layui.form,
            treetable = layui.treeTable;

        // 定义表格列配置
        const tableCols = [[
            { field: 'id', title: 'ID', width: 80, sort: true },
            { field: 'name', title: '案由名称', minWidth: 200 },
            { field: 'sort', title: '排序', width: 100, sort: true, edit: 'text' },
            {
                field: 'case_count', title: '关联案件数', width: 120, sort: true,
                templet: function(d) {
                    return d.case_count !== undefined && d.case_count !== null ? d.case_count : 0;
                }
            },
            {
                field: 'create_time', title: '创建时间', width: 160, sort: true,
                templet: function(d) { 
                    return d.create_time ? layui.util.toDateString(d.create_time*1000, "yyyy-MM-dd HH:mm") : ''; 
                }
            },
            { field: 'parent_id', title: '父级ID', width: 100, sort: true },
            { fixed: 'right', title: '操作', toolbar: '#tableBar', width: 220 }
        ]];

        //渲染树形表格
        function renderTreeTable() {
            var loadIndex = layer.load(1, {shade: [0.1, '#fff']});
            treetable.render({
                elem: '#treeTable', // 确保这个ID与HTML中的表格ID一致
                id: 'treeTableId',
                url: '/lawcase/casecause/index',
                page: false,
                toolbar: false,
                defaultToolbar: ['filter', 'exports', 'print'],
                tree: {
                    iconIndex: 1,
                    isPidData: false,
                    openAll: true,
                    idName: 'id',
                    childName: 'children',
                    emptyText: '暂无数据',
                    showField: 'name'
                },
                cols: tableCols,
                done: function(res, curr, count) {
                    layer.close(loadIndex);
                },
                parseData: function(res) { // 确保返回的数据结构正确

                    if (!res || !res.data || (Array.isArray(res.data) && res.data.length === 0)) {
                        return {code: 0, msg: '暂无数据', count: 0, data: []};
                    }

                    // 处理返回的数据结构
                    return {
                        code: 0,
                        msg: res.msg || '',
                        count: res.count || 0,
                        data: Array.isArray(res.data) ? res.data : (res.data.data || [])
                    }
                }
            });
        }

        renderTreeTable();

        // 暴露重新渲染方法到全局
        window.reloadTable = function() {
            renderTreeTable();
        };

        // 清空按钮点击事件
        $('#resetBtn').click(function() {
            $('#keywords').val('');
            renderTreeTable();
            layer.msg('已清空搜索条件', {
                icon: 1
            });
        });


        // 搜索表单提交
        form.on('submit(searchForm)', function (data) {
            var keywords = data.field.keywords;
            var loadIndex = layer.load(1, {shade: [0.1, '#fff']});

            if (!keywords) {
                renderTreeTable();
                layer.close(loadIndex);
                return false;
            }

            treetable.render({
                elem: '#treeTable',
                url: '/lawcase/casecause/index',
                where: { keywords: keywords },
                id: 'treeTableId', // 保持ID一致
                cols: tableCols,
                tree: {
                    iconIndex: 1,
                    isPidData: false,
                    openAll: true,
                    idName: 'id',
                    childName: 'children'
                },
                parseData: function(res) {
                    if (!res || !res.data) {
                        return { code: 0, msg: '暂无数据', count: 0, data: [] };
                    }
                    return {
                        code: 0,
                        msg: res.msg || '',
                        count: res.count || 0,
                        data: Array.isArray(res.data) ? res.data : (res.data.data || [])
                    };
                },
                done: function(res) {
                    layer.close(loadIndex);
                    if (!res.data || res.data.length === 0) {
                        layer.msg('没有找到匹配的数据', {icon: 0});
                    }
                }
            });
            return false;
        });

        // 添加案由按钮点击事件
        $('#addBtn').click(function() {
            tool.side("/lawcase/casecause/add", '添加案由');
        });

        // 表格操作事件
        treetable.on('tool(treeTable)', function (obj) {
            var data = obj.data;
            var layEvent = obj.event;
            if (layEvent === 'add') {
                tool.side("/lawcase/casecause/add?pid=" + data.id, '添加子级案由');
            } else if (layEvent === 'edit') {
                tool.side("/lawcase/casecause/edit?id=" + data.id, '编辑案由');
            } else if (layEvent === 'del') {
                layer.confirm('确定删除此案由吗？<br>如有子级案由或关联案件将无法删除', {
                    icon: 3,
                    title: '提示'
                }, function (index) {
                    tool.delete("/lawcase/casecause/delete", { id: data.id }, function (res) {
                            layer.msg(res.msg);
if (res.code === 0) {
                                reloadTable();
                            }
                    });
                    layer.close(index);
                });
            }
        });

        // 监听单元格编辑
        treetable.on('edit(treeTable)', function (obj) {
            var value = obj.value,
                data = obj.data;
            if (obj.field === 'sort') {
                tool.post("/lawcase/casecause/sort", {
                    id: data.id,
                    sort: value
                }, function (res) {
                    if (res.code === 0) {
                        layer.msg(res.msg);
                    } else {
                        layer.msg(res.msg);
                    }
                    reloadTable();
                });
            }
        });
    }
</script>
{/block}